package com.xydtech.ecard.config.service.impl;

import com.xydtech.common.constant.Constants;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.text.Convert;
import com.xydtech.common.utils.CacheUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.config.mapper.EcardApiSysConfigMapper;
import com.xydtech.ecard.config.service.IEcardApiSysConfigService;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 参数配置Service业务层处理
 *
 * @author busiplat
 * @date 2021-09-26
 */
@Service
public class EcardApiSysConfigServiceImpl implements IEcardApiSysConfigService {

    @Autowired
    private EcardApiSysConfigMapper ecardApiSysConfigMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey, Long deptId) {
        String configValue = Convert.toStr(CacheUtils.get(getCacheName(), getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        //查询改为多法人，归属的县级法人机构
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
        if (dept != null){
            config.setDeptId(dept.getDeptId());
        }
        SysConfig retConfig = ecardApiSysConfigMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            CacheUtils.put(getCacheName(), getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public SysConfig selectConfig(SysConfig config) {
        //查询改为多法人，归属的县级法人机构
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(config.getDeptId());
        if (dept != null){
            config.setDeptId(dept.getDeptId());
        }
        return ecardApiSysConfigMapper.selectConfig(config);
    }


    /**
     * 获取cache name
     *
     * @return 缓存名
     */
    private String getCacheName() {
        return Constants.SYS_CONFIG_CACHE;
    }


    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }
}
